<!-- eslint-disable vue/no-unused-components -->
<template>
  <div class="attraction-detail">
    <!-- 加载状态 -->
    <el-skeleton :loading="loading" animated :count="3">
      <template #template>
        <el-skeleton-item variant="h1" style="width: 50%" />
        <div class="skeleton-content">
          <el-skeleton-item variant="text" />
          <el-skeleton-item variant="text" style="width: 60%" />
        </div>
      </template>

      <!-- 主要内容 -->
      <template #default>
        <!-- 错误信息 -->
        <el-alert
          v-if="error"
          :title="error"
          type="error"
          show-icon
          class="error-alert"
        />

        <!-- 景点详情 -->
        <div v-if="attraction">
          <el-card class="detail-card">
            <!-- 标题区域 -->
            <div class="header">
              <h1 class="title">{{ attraction.name }}</h1>
              <div class="rating">
                <el-rate
                  v-model="attraction.rating"
                  disabled
                  show-score
                  :max="5"
                  :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                  score-template="{value} 分"
                />
              </div>
            </div>

            <!-- 景点图片 -->
            <el-card class="image-card">
              <template #header>
                <div class="image-header">
                  <el-icon><Picture /></el-icon>
                  <span>景点图片</span>
                </div>
              </template>
              <div class="image-container">
                <el-image 
                  v-if="attraction.image_url"
                  :src="attraction.image_url"
                  :preview-src-list="[attraction.image_url]"
                  fit="cover"
                  class="attraction-image"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>图片加载失败</span>
                    </div>
                  </template>
                </el-image>
                <div v-else class="no-image">
                  <el-icon><Picture /></el-icon>
                  <span>暂无图片</span>
                </div>
              </div>
            </el-card>

            <!-- 基本信息 -->
            <el-descriptions title="基本信息" border class="info-section">
              <el-descriptions-item label="地址">{{ attraction.address || '暂无' }}</el-descriptions-item>
              <el-descriptions-item label="开放时间">{{ attraction.opening_hours || '暂无' }}</el-descriptions-item>
              <el-descriptions-item label="门票价格">
                <el-tag type="warning">{{ attraction.ticket_price || 0 }} 元</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ attraction.contact_number || '暂无' }}</el-descriptions-item>
            </el-descriptions>

            <!-- 天气信息 -->
            <el-card 
              class="weather-card"
              :class="{ 'weather-card-clickable': !!weather }"
              @click="goToWeatherDetail"
            >
              <template #header>
                <div class="weather-header">
                  <el-icon><Sunny /></el-icon>
                  <span>实时天气</span>
                  <el-tag v-if="isDefaultWeather" type="info" size="small" style="margin-left: 10px;">
                    默认数据
                  </el-tag>
                </div>
              </template>
              <div v-if="weather" class="weather-content">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <div class="weather-item">
                      <el-icon><Cloudy /></el-icon>
                      <span class="value">{{ weather.weather }}</span>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="weather-item">
                      <el-icon><Thermometer /></el-icon>
                      <span class="label">温度：</span>
                      <span class="value">{{ weather.temperature }}°C</span>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="weather-item">
                      <el-icon><HeavyRain /></el-icon>
                      <span class="label">湿度：</span>
                      <span class="value">{{ weather.humidity }}%</span>
                    </div>
                  </el-col>
                </el-row>
                <el-row :gutter="20" class="weather-row">
                  <el-col :span="12">
                    <div class="weather-item">
                      <el-icon><WindPower /></el-icon>
                      <span class="label">风向：</span>
                      <span class="value">{{ weather.wind_direction }}</span>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="weather-item">
                      <el-icon><Fan /></el-icon>
                      <span class="label">风力：</span>
                      <span class="value">{{ weather.wind_power }}</span>
                    </div>
                  </el-col>
                </el-row>
                
                <!-- 天气建议区域 -->
                <div v-if="weather.advice" class="weather-advice">
                  <div class="advice-header">
                    <el-icon><Lightbulb /></el-icon>
                    <span>出行建议</span>
                  </div>
                  <div class="advice-content">
                    <p>{{ weather.advice.tips }}</p>
                    <div v-if="weather.advice.icons && weather.advice.icons.length > 0" class="advice-icons">
                      <el-tooltip 
                        v-for="(icon, index) in weather.advice.icons" 
                        :key="index" 
                        :content="getIconName(icon)" 
                        placement="top"
                      >
                        <el-icon :size="24" class="advice-icon" @click.stop>
                          <component :is="getIconComponent(icon)" />
                        </el-icon>
                      </el-tooltip>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="no-weather">
                暂无天气数据
              </div>
            </el-card>

            <!-- 用户评论 -->
            <el-card class="review-card">
              <template #header>
                <div class="review-header">
                  <el-icon><ChatLineSquare /></el-icon>
                  <span>用户评价（{{ attraction.reviews?.length || 0 }}条）</span>
                </div>
              </template>
              <div v-for="review in attraction.reviews" :key="review.id" class="review-item">
                <el-avatar :src="review.avatar" class="review-avatar" />
                <div class="review-content">
                  <div class="review-meta">
                    <span class="username">{{ review.username }}</span>
                    <el-rate
                      v-model="review.rating"
                      disabled
                      :max="5"
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                      class="review-rating"
                    />
                  </div>
                  <p class="comment">{{ review.comment }}</p>
                  <div class="review-time">
                    <el-icon><Timer /></el-icon>
                    <span>{{ review.created_at }}</span>
                  </div>
                </div>
              </div>
              <div v-if="!attraction.reviews?.length" class="no-reviews">
                暂无用户评价
              </div>
            </el-card>
          </el-card>
        </div>
      </template>
    </el-skeleton>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { 
  Timer,
  Picture,
  Sunny,
  Cloudy,
  Thermometer,
  HeavyRain,
  WindPower,
  Fan,
  ChatLineSquare,
  Lightbulb,
  Umbrella,
  Heat,
  Snowflake,
  ColdDrink,
  Watermelon,
  Scissor
} from '@element-plus/icons-vue'
import { getAttractionDetail, getWeather } from '@/api/attractions.js'
import { useRoute, useRouter } from 'vue-router'

export default {
  name: 'AttractionDetail',
  components: { 
    Timer,
    Picture,
    Sunny,
    Cloudy,
    Thermometer,
    HeavyRain,
    WindPower,
    Fan,
    ChatLineSquare,
    Lightbulb,
    Umbrella,
    Heat,
    Snowflake,
    ColdDrink,
    Watermelon,
    Scissor
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const attraction = ref(null)
    const weather = ref(null)
    const loading = ref(true)
    const error = ref(null)
    const id = ref(Number(route.params.id))
    const isDefaultWeather = ref(false) // 标记是否使用默认天气数据

    // 默认天气数据
    const defaultWeatherData = {
      weather: '晴',
      temperature: 25,
      humidity: 65,
      wind_direction: '东南风',
      wind_power: '3级',
      advice: {
        tips: '天气晴朗，适合户外活动，建议做好防晒措施',
        icons: ['sunny', 'water']
      }
    }

    const fetchAttractionData = async () => {
      try {
        const response = await getAttractionDetail(id.value)
        attraction.value = response.data
      } catch (err) {
        error.value = '获取景点详情失败，请稍后重试'
        console.error("获取详情失败", err)
      } finally {
        loading.value = false
      }
    }

const fetchWeatherData = async () => {
  try {
    if (attraction.value && attraction.value.address) {
      const response = await getWeather(attraction.value.address);
      
      // 调试日志（可选）
      console.log("完整响应:", response);
      console.log("状态码:", response.status);
      console.log("实际数据:", response.data);
      
      // 修正的数据处理逻辑
      if (response.data && response.status === 'success') {
        weather.value = response.data;
        isDefaultWeather.value = false;
        console.log(weather.value)
      } else {
        console.warn('天气数据获取失败，使用默认数据');
        weather.value = defaultWeatherData;
        isDefaultWeather.value = true;
      }
    }
  } catch (err) {
    console.error('获取天气数据失败，使用默认数据:', err);
    weather.value = defaultWeatherData;
    isDefaultWeather.value = true;
  }
};
    // 跳转到天气详情页面
    const goToWeatherDetail = () => {
      if (weather.value && attraction.value?.address) {
        router.push({
          path: '/weather',
          query: {
            address: attraction.value.address,
            weatherData: JSON.stringify(weather.value)
          }
        });
      }
    }

    // 图标映射方法
    const getIconComponent = (iconName) => {
      const iconMap = {
        'umbrella': Umbrella,
        'sunny': Sunny,
        'heat': Heat,
        'wind': WindPower,
        'snowflake': Snowflake,
        'cloudy': Cloudy,
        'water': ColdDrink,
        'scarf': Scissor,
        'watermelon': Watermelon
      }
      return iconMap[iconName] || Lightbulb
    }
    
    const getIconName = (iconName) => {
      const nameMap = {
        'umbrella': '雨具',
        'sunny': '晴天',
        'heat': '高温',
        'wind': '大风',
        'snowflake': '下雪',
        'cloudy': '多云',
        'water': '补水',
        'scarf': '保暖',
        'watermelon': '清凉'
      }
      return nameMap[iconName] || '提示'
    }

    onMounted(async () => {
      await fetchAttractionData()
      if (attraction.value) {
        await fetchWeatherData()
      }
    })

    return {
      attraction,
      weather,
      loading,
      error,
      isDefaultWeather,
      getIconComponent,
      getIconName,
      goToWeatherDetail
    }
  }
}
</script>

<style scoped lang="scss">
.attraction-detail {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;

  .detail-card {
    margin-top: 20px;

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .title {
        font-size: 24px;
        color: #303133;
      }
    }

    .image-card {
      margin: 20px 0;

      .image-header {
        display: flex;
        align-items: center;
        .el-icon {
          margin-right: 8px;
          font-size: 20px;
          color: #409EFF;
        }
      }

      .image-container {
        height: 400px;
        border-radius: 8px;
        overflow: hidden;
        
        .attraction-image {
          width: 100%;
          height: 100%;
          transition: transform 0.3s;
          
          &:hover {
            transform: scale(1.05);
          }
        }

        .image-error, .no-image {
          height: 200px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #909399;
          
          .el-icon {
            font-size: 40px;
            margin-bottom: 10px;
          }
        }
      }
    }

    .info-section {
      margin: 20px 0;
    }

    .weather-card {
      margin: 20px 0;
      transition: all 0.3s;
      cursor: default;

      &.weather-card-clickable {
        cursor: pointer;
        
        &:hover {
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
          transform: translateY(-2px);
          
          .weather-header {
            color: #409EFF;
          }
        }
      }

      .weather-header {
        display: flex;
        align-items: center;
        .el-icon {
          margin-right: 8px;
          font-size: 20px;
          color: #409EFF;
        }
      }

      .weather-content {
        .weather-item {
          display: flex;
          align-items: center;
          padding: 12px 0;

          .el-icon {
            font-size: 24px;
            margin-right: 8px;
            color: #67C23A;
          }

          .value {
            font-size: 18px;
            font-weight: bold;
            color: #606266;
          }

          .label {
            color: #909399;
            margin-right: 6px;
          }
        }

        .weather-row {
          margin-top: 15px;
        }
      }

      .no-weather {
        text-align: center;
        color: #909399;
        padding: 20px;
      }
      
      // 天气建议样式
      .weather-advice {
        margin-top: 20px;
        padding: 15px;
        background-color: #f8f9fa;
        border-radius: 8px;
        border-left: 4px solid #e6a23c;
        
        .advice-header {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          font-weight: bold;
          color: #e6a23c;
          
          .el-icon {
            margin-right: 8px;
            font-size: 20px;
            color: #e6a23c;
          }
        }
        
        .advice-content {
          p {
            margin-bottom: 10px;
            line-height: 1.6;
            color: #606266;
            font-size: 15px;
          }
        }
        
        .advice-icons {
          display: flex;
          justify-content: center;
          gap: 15px;
          margin-top: 10px;
          
          .advice-icon {
            color: #409eff;
            transition: transform 0.3s;
            cursor: pointer;
            
            &:hover {
              transform: scale(1.2);
            }
          }
        }
      }
    }

    .review-card {
      margin-top: 20px;

      .review-header {
        display: flex;
        align-items: center;
        .el-icon {
          margin-right: 8px;
          color: #E6A23C;
        }
      }

      .review-item {
        display: flex;
        padding: 15px 0;
        border-bottom: 1px solid #ebeef5;

        .review-avatar {
          margin-right: 15px;
        }

        .review-content {
          flex: 1;

          .review-meta {
            display: flex;
            align-items: center;
            margin-bottom: 8px;

            .username {
              font-weight: bold;
              margin-right: 15px;
            }
          }

          .comment {
            color: #606266;
            line-height: 1.6;
          }

          .review-time {
            margin-top: 8px;
            color: #909399;
            display: flex;
            align-items: center;

            .el-icon {
              margin-right: 5px;
            }
          }
        }
      }

      .no-reviews {
        text-align: center;
        color: #909399;
        padding: 20px;
      }
    }
  }

  .error-alert {
    margin: 20px 0;
  }
}
</style>